package com.envper.common.service.impl;

import com.envper.common.config.MinioConfiguration;
import com.envper.mysql.domain.Status;
import com.envper.common.exception.GlobalException;
import com.envper.common.service.FileService;
import com.envper.common.util.MinioUtils;
import io.minio.ObjectWriteResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@RequiredArgsConstructor
@Slf4j
public class FileServiceImpl implements FileService {
    private final MinioUtils minioUtils;
    private final MinioConfiguration minioConfiguration;

    @Override
    public String uploadAvatar(MultipartFile file, Long id, String path) {
        return "";
    }

    @Override
    public String uploadAvatar(MultipartFile avatar, Long userId) {
        String bucketName = minioConfiguration.getBucketName();
        String type = "";
        if (avatar.getOriginalFilename() != null) {
            String[] split = avatar.getOriginalFilename().split("\\.");
            type = split[split.length - 1];
        }
        String imageName = "/avatar/" + userId + "." + type;
        ObjectWriteResponse objectWriteResponse = minioUtils.uploadFile(bucketName, avatar, imageName, avatar.getContentType());
        if (objectWriteResponse == null) {
            throw new GlobalException(Status.UPLOADERROR);
        }
        return minioConfiguration.getUrl() + imageName;
    }

    @Override
    public String uploadFile(MultipartFile file, String url) {
        String bucketName = minioConfiguration.getBucketName();
        String type = "";
        if (file.getOriginalFilename() != null) {
            String[] split = file.getOriginalFilename().split("\\.");
            type = split[split.length - 1];
        }
        String fileName = url + "." + type;
        ObjectWriteResponse objectWriteResponse = minioUtils.uploadFile(bucketName, file, fileName, file.getContentType());
        if (objectWriteResponse == null) {
            throw new GlobalException(Status.UPLOADERROR);
        }
        return minioConfiguration.getUrl() + fileName;
    }
}
